namespace SimpleWebServices.IO
{
    using System;
    using System.IO;
    using System.Web;
    using SimpleWebServices.Data;

    public sealed class HttpRequestBaseFile : IDisposable
    {
        private bool _disposed;

        public HttpRequestBaseFile(HttpRequestBase request)
        {
            if (null == request)
            {
                throw new ArgumentNullException("request");
            }

            this.Info = new FileInfo(Token.New() + ".txt");
            using (FileStream file = File.Open(this.Info.FullName, FileMode.CreateNew, FileAccess.Write, FileShare.None))
            {
                using (StreamWriter writer = new StreamWriter(file))
                {
                    writer.Write(request.HttpMethod);
                    writer.Write(' ');
                    writer.Write(request.Url.PathAndQuery);
                    writer.Write(Environment.NewLine);
                    for (int i = 0; i < request.Headers.Count; i++)
                    {
                        writer.Write(request.Headers.Keys[i]);
                        writer.Write(": ");
                        writer.Write(request.Headers[i]);
                        writer.Write(Environment.NewLine);
                    }

                    writer.Write(Environment.NewLine);
                    if (null != request.InputStream && request.InputStream.CanRead)
                    {
                        using (StreamReader reader = new StreamReader(request.InputStream))
                        {
                            writer.Write(reader.ReadToEnd());
                        }
                    }
                }
            }

            this.Info.Refresh();
        }

        ~HttpRequestBaseFile()
        {
            this.Dispose(false);
        }

        public FileInfo Info
        {
            get;
            private set;
        }

        public FileStream Open()
        {
            return File.Open(this.Info.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!this._disposed)
            {
                if (disposing)
                {
                    this.Info.Refresh();
                    if (this.Info.Exists)
                    {
                        File.Delete(this.Info.FullName);
                    }
                }

                this._disposed = true;
            }
        }
    }
}